<?php

declare(strict_types=1);

namespace App\Chat\Controller;

use App\Chat\Annotation\ChatAuth;
use App\Chat\Service\EmployeeService;
use App\CustHub\Model\ChContact;
use App\CustHub\Model\ChEmployee;
use App\CustHub\Service\ChContactService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;

#[Controller(prefix: 'ch/chat/contact'),ChatAuth]
class  ContactController extends ChatBaseController
{
    #[Inject]
    protected EmployeeService $service;

    #[Inject]
    protected ChContactService $contactService;

    #[PostMapping('getContactList')]
    public function getContactList()
    {
        $data = $this->request->all();
        $data['main_uid'] =  \Hyperf\Context\Context::get('main_uid');

        $list = ChContact::query()
            ->select(['id','nickname','avatar','user_id','corp_short_name as corp_name','is_wechat'])
            ->where('main_uid',$data['main_uid'])
            ->where('robot_id',$data['robot_id'])
            ->get()
            ->groupBy('corp_name')->toArray();

        uksort($list, function($a, $b) {
            if ($a === "微信") {
                return -1; // "微信"始终排在最前面
            }
            if ($b === "微信") {
                return 1; // "微信"始终排在最前面
            }
            return strcmp($a, $b); // 其他按原顺序或字母顺序
        });

        $contactList = [];

        foreach ($list as $key => $value) {
            $contactList[] = [
                'corp_name' => $key == '微信' ? '微信好友' : $key,
                'list' => $value,
            ];
        }

        return $this->success($contactList);
    }

    /**
     * 获取员工列表
     */
    #[PostMapping('getEmployeeList')]
    public function getEmployeeList(): \Psr\Http\Message\ResponseInterface
    {
        $data = $this->request->all();
        $data['main_uid'] =  \Hyperf\Context\Context::get('main_uid');
        return $this->success($this->service->list($data));
    }

    #[PostMapping('searchList')]
    public function searchList(): \Psr\Http\Message\ResponseInterface
    {
        $data = $this->request->all();
        $data['main_uid'] =  \Hyperf\Context\Context::get('main_uid');

        return $this->success($this->service->searchList($data));
    }
}